package com.carrot.uaa.util;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @description:
 * @author: zl
 * @date: 2023/11/20
 */
public class IpAddressUtil {

    public static String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        // If the above headers didn't provide a valid IP, try extracting from X-Real-IP header
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("X-Real-IP");
        }

        // If the IP is still not found, use a default value
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = "0.0.0.0";
        }

        // If the IP contains a comma (',') due to multiple proxies, use the first part
        int commaPos = ipAddress.indexOf(',');
        if (commaPos > 0) {
            ipAddress = ipAddress.substring(0, commaPos);
        }

        return ipAddress.trim();
    }
}
